import plugin from '../../../lib/plugins/plugin.js'
import fetch from 'node-fetch'
import { checkCD, cancelCD } from "../model/CD.js";
import { initImpart } from "../model/InitImpart.js"

var api = "http://116.205.185.208:7002/impart?";
export class impact extends plugin {
    constructor() {
        super({
            /** 功能名称 */
            name: 'impart系统',
            /** 功能描述 */
            dsc: '多人在线银趴系统',
            /** https://oicqjs.github.io/oicq/#events */
            event: 'message',
            /** 优先级，数字越小等级越高 */
            priority: 3000,
            rule: [
                {
                    reg: "^#?生成牛牛$",
                    fnc: 'create'
                },
                {
                    reg: "^#?remake$",
                    fnc: 'remake'
                },
                {
                    reg: "^#?开导|打胶$",
                    fnc: 'ziwei'
                },
                {
                    reg: "^#?嗦牛牛$",
                    fnc: 'suo'
                },
                {
                    reg: "^#?决斗$",
                    fnc: 'playerpk'
                },
                {
                    reg: "^#?精神状态查看|查看$",
                    fnc: 'query'
                },
                {
                    reg: "^#?今日排行$",
                    fnc: 'playergrouprank'
                }
            ]
        }
        )
    }

    async create(e) {
        if ( initImpart(e) == false) {
            this.reply('本群银趴还未开始，请联系主人开启哦')
            return false
        }
        if (!e.isGroup) {
            e.reply('请在群聊执行')
            return false
        }
        let url = api + "fun=create&qq_myself=" + e.user_id + "&qqgroup_myself=" + e.group_id
        let res = await fetch(url).catch((err) => logger.error(err));
        if (!res) {
            return await this.reply('接口请求失败,请先更新插件或联系群433567006')
        }
        let symbols = Object.getOwnPropertySymbols(res);
        let internals = res[symbols[1]];
        let status = internals.status;
        //console.log(status);
        if (status === 200) {
            res = await res.text()
            let str = res;
            str = await this.fix(str)
            await this.reply(`${str}`)
        } else {
            e.reply("未知错误");
        }
    }

    async remake(e) {
        if ( initImpart(e) == false) {
            this.reply('本群银趴还未开始，请联系主人开启哦')
            return false
        }
        if (!e.isGroup) {
            e.reply('请在群聊执行')
            return false
        }
        let url = api + "fun=remake&qq_myself=" + e.user_id + "&qqgroup_myself=" + e.group_id
        let res = await fetch(url).catch((err) => logger.error(err));
        if (!res) {
            return await this.reply('接口请求失败,请先更新插件或联系群433567006')
        }
        let symbols = Object.getOwnPropertySymbols(res);
        let internals = res[symbols[1]];
        let status = internals.status;
        //console.log(status);
        if (status === 200) {
            res = await res.text()
            let str = res;
            str = await this.fix(str)
            await this.reply(`${str}`)
        } else {
            e.reply("未知错误");
        }
    }

    async ziwei(e) {
        if ( initImpart(e) == false) {
            this.reply('本群银趴还未开始，请联系主人开启哦')
            return false
        }
        if (!e.isGroup) {
            e.reply('请在群聊执行')
            return false
        }
        // 检查是否触发了cd
        let isCD = await checkCD(e);
        // 如果触发了cd，直接返回
        if (isCD) {
            let msg = await checkCD(e)
            this.reply(msg)
            return true
        }
        let url = api + "fun=ziwei&qq_myself=" + e.user_id
        let res = await fetch(url).catch((err) => logger.error(err));
        if (!res) {
            return await this.reply('接口请求失败,请先更新插件或联系群433567006')
        }
        let symbols = Object.getOwnPropertySymbols(res);
        let internals = res[symbols[1]];
        let status = internals.status;
        if (status === 200) {
            res = await res.text()
            let str = res;
            str = await this.fix(str)
            await this.reply(`${str}`)
            // 取消cd
            await cancelCD(e, str)
        } else {
            e.reply("未知错误");
        }
        return true;
    }

    async suo(e) {
        if ( initImpart(e) == false) {
            this.reply('本群银趴还未开始，请联系主人开启哦')
            return false
        }
        if (!e.isGroup) {
            e.reply('请在群聊执行')
            return false
        }
        let atCount = e.message.filter(item => item.type == 'at').length;
        if (atCount > 1) {
            e.reply(`艾特那么多人你干嘛哎呦`);
            return false
        }
        // 检查是否触发了cd
        let isCD = await checkCD(e);
        // 如果触发了cd，直接返回
        if (isCD) {
            let msg = await checkCD(e)
            this.reply(msg)
            return true
        }
        let qq_pk;
        // 如果有艾特的人，取艾特的人扣扣号，没有就自己
        if (e.at) {
            qq_pk = e.at;
        } else {
            qq_pk = e.user_id;
        }
        let url = api + "fun=suo&qq_myself=" + e.user_id + "&qq_pk=" + qq_pk;
        let res = await fetch(url).catch((err) => logger.error(err));
        if (!res) {
            return await this.reply('接口请求失败,请先更新插件或联系群433567006')
        }
        let symbols = Object.getOwnPropertySymbols(res);
        let internals = res[symbols[1]];
        let status = internals.status;
        //console.log(status);
        if (status === 200) {
            res = await res.text()
            let str = res;
            str = await this.fix(str)
            let first;
            let second;
            // 如果没艾特别人，替换成自己
            if (qq_pk === e.user_id) {
                // 提取出第一个【】之间的内容
                first = str.slice(str.indexOf("【") + 1, str.indexOf("】"));
                // 提取出第二个【】之间的内容
                second = str.slice(str.lastIndexOf("【") + 1, str.lastIndexOf("】"));
                // 判断两个内容是否相等,相等把【】换成自己
                if (first === second) {
                    let count = 0;
                    str = str.replace(/【.*?】/g, function (match) { count++; return count === 2 ? '自己' : match; });
                    str = str.replace(/对方/g, '自己');
                    await this.reply(`${str}`)
                }
            } else {
                await this.reply(`${str}`)
            }
            // 取消cd
            await cancelCD(e, str)
        } else {
            e.reply("未知错误");
        }
    }

    async playerpk(e) {
        if ( initImpart(e) == false) {
            this.reply('本群银趴还未开始，请联系主人开启哦')
            return false
        }
        if (!e.isGroup) {
            e.reply('请在群聊执行')
            return false
        }
        let atCount = e.message.filter(item => item.type == 'at').length;
        if (atCount > 1) {
            e.reply(`艾特那么多人你干嘛哎呦`);
            return false
        }
        let qq_pk;
        // 如果有艾特的人，取艾特的人扣扣号，没有就自己
        if (e.at === e.user_id) {
            e.reply("打自己是吧，会影分身再来吧")
            return false
        }
        if (e.at) {
            qq_pk = e.at;
        } else {
            e.reply(`请艾特你的击剑对象`)
            return false
        }
         // 检查是否触发了cd
         let isCD = await checkCD(e);
         // 如果触发了cd，直接返回
         if (isCD) {
             let msg = await checkCD(e)
             this.reply(msg)
             return true
        }
        let url = api + "fun=pk&qq_myself=" + e.user_id + "&qq_pk=" + qq_pk;
        let res = await fetch(url).catch((err) => logger.error(err));
        if (!res) {
            return await this.reply('接口请求失败,请先更新插件或联系群433567006')
        }
        let symbols = Object.getOwnPropertySymbols(res);
        let internals = res[symbols[1]];
        let status = internals.status;
        //console.log(status);
        if (status === 200) {
            res = await res.text()
            let str = res;
            str = await this.fix(str)
            await this.reply(`${str}`)
            await cancelCD(e, str)
        } else {
            e.reply("你的或者对方的牛牛还没长出来，快去群里#生成牛牛吧！");
        }
        return true;
    }

    async query(e) {
        if ( initImpart(e) == false) {
            this.reply('本群银趴还未开始，请联系主人开启哦')
            return false
        }
        if (!e.isGroup) {
            e.reply('请在群聊执行')
            return false
        }
        let qq = e.message.filter(item => item.type == 'at')?.map(item => item?.qq);
        if (qq == "") {
            let url = api + "fun=query&qq_myself=" + e.user_id;
            let res = await fetch(url).catch((err) => logger.error(err));
            if (!res) {
                return await this.reply('接口请求失败,请先更新插件或联系群433567006')
            }
            let symbols = Object.getOwnPropertySymbols(res);
            let internals = res[symbols[1]];
            let status = internals.status;
            //console.log(status);
            if (status === 200) {
                res = await res.text()
                let str = res;
                str = await this.fix(str)
                await this.reply(`${str}`)
            } else {
                e.reply("牛牛还没长出来，快去群里#生成牛牛吧！");
            }
        } else {
            let url = api + "fun=query&qq_myself=" + qq;
            let res = await fetch(url).catch((err) => logger.error(err));
            if (!res) {
                return await this.reply('接口请求失败,请先更新插件或联系群433567006')
            }
            let symbols = Object.getOwnPropertySymbols(res);
            let internals = res[symbols[1]];
            let status = internals.status;
            //console.log(status);
            if (status === 200) {
                res = await res.text()
                let str = res;
                str = await this.fix(str)
                await this.reply(`${str}`)
            } else {
                e.reply("你的牛牛还没长出来，快去群里#生成牛牛吧！");
            }
        }

    }

    async fix(str) {
        // 如果输入为空或者不包含数字，直接返回原字符串
        if (!str || !/\d/.test(str)) {
            return str;
        }
        let nums = [];
        let names = [];
        let name = [];
        str = str.replace(/\d{8,}/g, (match) => {
            nums.push(match);
            return 'AAAA';
        });
        if (this.e.isGroup) {
            var mum_qq = nums
            for (let qq of mum_qq) {
                // qq是数组里的每个元素
                let member = await Bot.getGroupMemberInfo(this.e.group_id, qq);
                //console.log(member)
                names.push(member.card || member.nickname); // 把member.card添加到names数组的末尾,如果左边为假就换nickname
            }
            let index = 0; // 用来记录当前替换的name数组的索引
            str = str.replace(/AAAA/g, () => {
                name = names[index]; // 获取当前索引对应的name数组元素
                index++; // 索引加一
                if (index >= names.length) {
                    index = 0; // 如果索引超过了name数组的长度，就重置为零
                }
                return name; // 返回替换后的字符串
            });
            //console.log(str);
        } else {
            name = mum_qq;
            //console.log(name);
        }
        str = str.slice(1, -1);
        return str;
    }

    async playergrouprank(e) {
        if ( initImpart(e) == false) {
            this.reply('本群银趴还未开始，请联系主人开启哦')
            return false
        }
        if (!e.isGroup) {
            e.reply('请在群聊执行')
            return false
        }
        let url = api + "fun=player_group_rank&qqgroup_myself=" + e.group_id
        console.log(url)
        let res = await fetch(url).catch((err) => logger.error(err));
        if (!res) {
            return await this.reply('接口请求失败,请先更新插件或联系群433567006')
        }
        let symbols = Object.getOwnPropertySymbols(res);
        let internals = res[symbols[1]];
        let status = internals.status;
        //console.log(status);
        if (status === 200) {
            res = await res.text();
            let str = res;
            str = await this.fix(str)
            str = str.replace(/\\n/g, "\n");
            console.log(str);
            await e.reply(`${str}`);
        } else {
            e.reply("未知错误");
        }
    }
}